'use strict';
const { Service } = require('egg');
const Result = require('../util/result');

class AdminService extends Service {

  async list() {
    const lists = await this.ctx.model.Admin.findAll({
      attributes: {
        exclude: ['password'],
      },
    });
    return Result.success(lists);
  }

  async create(data) {
    const udata = await this.isExist(data.admin_name);
    if (udata) return Result.warn(-1, '用户已存在');
    const bcrypt = require('bcryptjs');
    const salt = bcrypt.genSaltSync(10);
    const hash = bcrypt.hashSync(data.password, salt);
    data.password = hash;
    const info = await this.ctx.model.Admin.create({ ...data });
    if (!info) return Result.fail();
    const res = {
      id: info.admin_id,
      name: info.admin_name,
      phone: info.phone,
    };
    return Result.success(res);
  }

  async login(data) {
    const bcrypt = require('bcryptjs');
    const udata = await this.isExist(data.admin_name);
    if (!udata) return Result.warn(-1, '不存在');
    if (!bcrypt.compareSync(data.password, udata.password)) return Result.warn(-1, '密码错误');
    const res = {
      id: udata.admin_id,
      name: udata.admin_name,
      phone: udata.phone,
      level: udata.level,
    };
    return Result.success(res);
  }

  async update(data) {
    const info = await this.ctx.model.Admin.update({ ...data }, {
      where: {
        admin_id: data.admin_id,
      },
    });
    if (info[0] > 0) {
      const res = await this.findOne(data.admin_id);
      return Result.success(res);
    }
    return Result.fail();
  }

  async delete(data) {
    const res = await this.ctx.model.Admin.destroy({
      where: { admin_id: data.admin_id },
    });
    if (res > 0) {
      return Result.success(null);
    }
    return Result.fail();
  }

  async findById(id) {
    const info = await this.ctx.model.Admin.findByPk(id);
    return info;
  }

  async isExist(name) {
    const info = await this.ctx.model.Admin.findOne({
      where: {
        admin_name: name,
      },
    });
    return info;
  }

  async findOne(id) {
    const info = await this.ctx.model.Admin.findOne({
      where: {
        admin_id: id,
      },
      attributes: { exclude: ['password'] },
    });
    return info;
  }

}

module.exports = AdminService;
